package cn.yogehaoren.demo.producer;


import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

/**
 * @author WangNing
 * @since 1.0
 */
@Component
public class RabbitSender implements RabbitTemplate.ConfirmCallback , RabbitTemplate.ReturnCallback {


    static private final String EXCHANGE = "exchange-1";

    static private final String ROUTE_KEY = "springboot.hello";

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(byte[] rawMessage, MessageProperties properties) throws Exception {

        Message message = new Message(rawMessage, properties);
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend(EXCHANGE, ROUTE_KEY, message, correlationData);
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    public void send(byte[] rawMessage, Map<String, Object> headers) throws Exception {
        MessageProperties properties = new MessageProperties();
        headers.forEach(properties::setHeader);
        send(rawMessage, properties);
    }


    @Value("${consumer.exchange}")
    private String exchange2;

    public void sendOrder(String order) throws Exception {

        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend(exchange2, "springboot.222", order);
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    // 确认消息, 监听器
    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        System.out.println("############## Confirm ##############");
        System.out.println("CorrelationData: "+correlationData);
        System.out.println("cause: "+cause);
        System.out.println("ACK: "+ack);
        if(!ack){
            System.out.println("  NACK 异常处理");
        }
    }

    // 消息不可达, 监听器
    @Override
    public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.out.println("############## Return ##############");
        System.out.println("return exchange:  "+ exchange);
        System.out.println("return routingKey: "+ routingKey);
        System.out.println("return messageBody: "+ new String(message.getBody()));
        System.out.println("return replyCode: "+ replyCode);
        System.out.println("return replyText: "+ replyText);
    }

}
